package com.chengh.nami.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chengh.nami.common.exception.BizException;
import com.chengh.nami.system.mapper.SysRoleMenuMapper;
import com.chengh.nami.system.pojo.SysRoleMenu;
import com.chengh.nami.system.service.ISysRoleMenuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author chengh
 */
@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements ISysRoleMenuService {

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateRoleMenus(Long roleId, List<Long> menuIds) {
        // 需要先删除角色的所有菜单
        this.baseMapper.delete(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId, roleId));
        // 在将待分配的数据插入进去
        if (CollectionUtils.isEmpty(menuIds)) {
            throw new BizException("分配的菜单信息不能为空！");
        }
        ArrayList<SysRoleMenu> sysRoleMenus = new ArrayList<>(8);
        for (Long menuId : menuIds) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(roleId);
            sysRoleMenu.setMenuId(menuId);
            sysRoleMenus.add(sysRoleMenu);
        }
        return this.saveBatch(sysRoleMenus);
    }
}
